import { AxiosResponse } from 'axios'

export const isFileDownloadResponse = (response: AxiosResponse): boolean => {
  return response.headers['content-disposition']?.includes('attachment') || false
}

export const handleFileDownload = (response: AxiosResponse): void => {
  const fileName = response.headers['content-disposition']?.split('filename=')[1]?.replace(/['"]/g, '') || 'download'
  const url = URL.createObjectURL(response.data)
  const link = document.createElement('a')
  link.href = url
  link.download = fileName
  document.body.append(link)
  link.click()
  URL.revokeObjectURL(url)
  link.remove()
}

// 转换对象的所有键为蛇形命名法
export const transformKeysToSnakeCase = (data: any): any => {
  if (data === null || typeof data !== 'object') {
    return data
  }

  if (data instanceof Date) {
    return data
  }

  if (Array.isArray(data)) {
    return data.map(transformKeysToSnakeCase)
  }

  return Object.keys(data).reduce((acc: Record<string, any>, key) => {
    const snakeKey = key.replace(/([A-Z])/g, '_$1').toLowerCase()
    acc[snakeKey] = transformKeysToSnakeCase(data[key])
    return acc
  }, {})
}
